package net.xdclass.service.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.xdclass.service.domain.ProductOrder;
import net.xdclass.service.service.OrderService;
import net.xdclass.service.service.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.UUID;

/**
 * author: 何建文
 * create: 2020-07-18 16:38
 * description:
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;

    private final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    /**
     * ribbon模式
     */
    /*@Override
    public ProductOrder save(int userId, int productId) {
        // 获取商品详情
        Map<String, Object> productMap = restTemplate.getForObject("http://product-service/api/v1/product/findById?id=" + productId, Map.class);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setCreaTime(new Date());
        productOrder.setPrice(Integer.parseInt(productMap.get("price").toString()));
        productOrder.setProductName(productMap.get("name").toString());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());
        return productOrder;
    }*/

    /**
     * feign模式
     * @param userId
     * @param productId
     * @return
     */
    @Override
    public ProductOrder save(int userId, int productId) {
        logger.info("order service save");
        // 获取商品详情
        String result = productClient.findById(productId);
        System.out.println(result);
        JSONObject object = JSON.parseObject(result);

        ProductOrder productOrder = new ProductOrder();
        productOrder.setPrice(object.getInteger("price"));
        productOrder.setProductName(object.getString("name"));
        productOrder.setCreaTime(new Date());
        productOrder.setUserId(userId);
        productOrder.setTradeNo(UUID.randomUUID().toString());
        return productOrder;
    }
}
